﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileEncodingConvertor
{
    public partial class PreviewForm : Form
    {
        string[] files;

        public PreviewForm(string[] files)
        {
            InitializeComponent();
            this.files = files;
        }

        private void buttonProcess_Click(object sender, EventArgs e)
        {
            progressBar.Visible = true;
            progressBar.Maximum = files.Length;
            progressBar.Step = 1;
            buttonProcess.Enabled = false;

            for (int i = 0; i < listView.Items.Count; i++)
            {
                ListViewItem item = listView.Items[i];
                string filename = item.SubItems[0].Text;
                try
                {
                    string text = File.ReadAllText(filename);
                   // File.WriteAllText(filename, text, Encoding.ASCII);
                    File.WriteAllText(filename, System.Text.RegularExpressions.Regex.Replace(text, "(?<!\r)\n", "\r\n"));//, Encoding.ASCII);
                    item.SubItems[1].Text = "Processed";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, filename);
                    item.SubItems[1].Text = "Error";
                }
                listView.FocusedItem = item;

                progressBar.PerformStep();
            }

            progressBar.Visible = false;
            buttonProcess.Text = "Done";
        }

        private void PreviewForm_Load(object sender, EventArgs e)
        {
            foreach (var item in files)
            {
                listView.Items.Add(new ListViewItem(new string[] { item.Replace("\\\\", "\\"), "Pending" }));
            }
            textBoxTotalCount.Text = files.Length.ToString();
        }
    }
}
